/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package deti.es.ukni.cm.account;

import deti.es.persistence.account.AccountDoesNotExist;
import deti.es.persistence.account.WrongPassword;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet to login in the system.
 *
 * @author ukni
 */
public class login extends HttpServlet {
   

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        HttpSession session = request.getSession(true);
        AccountBean acc = (AccountBean) session.getAttribute("account");
        if ( acc != null ){
            /*  already loged in */
            response.sendRedirect("./");
        }else{
            try {
                acc = new AccountBean(request.getParameter("username"), request.getParameter("pwd"));
                session.setAttribute("account", acc);
            } catch (AccountDoesNotExist ex) {
                session.setAttribute("message", ex.getMessage() );
            } catch (WrongPassword ex ){
                session.setAttribute("message", ex.getMessage() );
            }

            if (acc != null && acc.hasBand() ){
                response.sendRedirect("../band/new.jsp");
            }else{
                response.sendRedirect("./");
            }
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
